package com.controller;

import com.entity.FinanceFlow;
import com.entity.FinanceLoanInfo;
import com.entity.FinanceAccount;
import com.service.FinanceLoanInfoService;
import com.service.FinanceAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * 财务管理
 */

@RestController
@RequestMapping("/api/finance")
public class FinanceController {

    @Autowired
    private FinanceLoanInfoService loanInfoService;

    @Autowired
    private FinanceAccountService accountService;


    @GetMapping("/loan")
    public Page<FinanceLoanInfo> getAllLoansPage(@RequestParam(defaultValue = "1") int page,
                                             @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return loanInfoService.findAll(pageable);
    }

    @GetMapping("/loan/{id}")
    public Optional<FinanceLoanInfo> getLoanById(@PathVariable Integer id) {
        return loanInfoService.findById(id);
    }

    @PostMapping("/loan")
    public FinanceLoanInfo saveLoan(@RequestBody FinanceLoanInfo loanInfo) {
        return loanInfoService.save(loanInfo);
    }

    @DeleteMapping("/loan/{id}")
    public void deleteLoan(@PathVariable Integer id) {
        loanInfoService.deleteById(id);
    }

    //////////////////////////////

    @GetMapping("/account")
    public Page<FinanceAccount> getAllAccounts(@RequestParam(defaultValue = "1") int page,
                                               @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return accountService.findAll(pageable);
    }
    @GetMapping("/account/{id}")
    public Optional<FinanceAccount> getAccountById(@PathVariable Integer id) {
        return accountService.findById(id);
    }


    @PostMapping("/account/flow")
    public void saveFlow(@RequestBody FinanceFlow flow) {
        accountService.saveFlow(flow);
    }


    @DeleteMapping("/account/{id}")
    public void deleteAccount(@PathVariable Integer id) {
        accountService.deleteById(id);
    }

    @DeleteMapping("/account/flow/{id}")
    public void deleteAccountFlow(@PathVariable Integer id) {
        accountService.deleteFlowById(id);
    }
}